import QtQuick 1.1
import com.nokia.meego 1.0
import com.nokia.extras 1.0
import "calcJSLib.js" as CalcJSLib

Page {
    id: mainPage
    tools: commonTools

    Rectangle {
        id: container
        color: "#4c0094"        

        anchors.left: parent.left
        anchors.leftMargin: 0
        anchors.top: parent.top
        width: mainPage.width
        height: mainPage.height

        gradient: Gradient {
            GradientStop {
                position: 0.00;
                color: "#c7b8fa";
            }
            GradientStop {
                position: 0.60;
                color: "#ffffff";
            }
        }

        SipAttributes {
            id:customSipAttributes
            actionKeyEnabled: true
            actionKeyHighlighted: true
            actionKeyLabel: qsTr("Calculate")
        }

        Row {
            id: rowAppLogoName

            Image {
                id: appLogo
                x: 0; y: 0
                width: 64; height: 64
                source: "qrc:/icon_withoutBG"
                MouseArea {
                    anchors.fill: parent
                    onClicked: appWindow.pageStack.push(aboutPage)
                }
            }

            Text {
                id: txtAppName
                x: 80
                y: 10
                width: mainPage.width - x
                text: qsTr("Time Calculator")
                font.pixelSize: 30
                font.bold: true
                // horizontalAlignment: Text.AlignHCenter
                color: "#3f0064"
                MouseArea {
                    anchors.fill: parent
                    onClicked: appWindow.pageStack.push(aboutPage)
                }
            }

        }


        Flickable {
            id: flick
            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.top: rowAppLogoName.bottom

            contentHeight: container.width>=800 ? container.height * 1.6 : container.height * 1

            width: container.width
            height: container.height
            clip: true

            flickableDirection: Flickable.VerticalFlick
            boundsBehavior: Flickable.DragOverBounds


            Row {
                x: 10
                y: 30

                Text {
                    width: mainPage.width - x
                    text: qsTr("Plus/Minus Time")
                    font.pixelSize: 25
                    font.bold: true
                    color: "#800078"
                }
            }

            Row {
                id: rowDatePicker
                x: 10
                y: 80

                Button{
                    id: btnSelectDate
                    width: 150
                    text: qsTr("Date")
                    opacity: 0.5
                    onClicked: launchDialogToToday()
                }

                Text {
                    id: txtSelectedDate
                    color: "#666666"
                    anchors.left: btnSelectDate.right
                    anchors.leftMargin: 20
                    anchors.top: btnSelectDate.top
                    anchors.topMargin: 10
                    font.pointSize: 18
                }

            }
            Row {
                id: rowTimePicker
                x: 10
                y: 150


                Button{
                    id: btnSelectTime
                    width: 150
                    text: qsTr("Time")
                    opacity: 0.5
                    onClicked: launchDialogToTime()
                }

                Text {
                    id: txtSelectedTime
                    color: "#666666"
                    anchors.left: btnSelectTime.right
                    anchors.leftMargin: 20
                    anchors.top: btnSelectTime.top
                    anchors.topMargin: 10
                    font.pointSize: 18
                }


            }

            Row {
                id: rowDateOperation
                x: 10
                y: 220
                width: parent.width


                ButtonRow {
                    width: 150
                    checkedButton: btnPlus
                    Button {
                        id: btnPlus
                        text: "+"
                        opacity: 0.8
                        onClicked: {
                            calcResults()
                        }
                    }

                    Button {
                        id: btnMinus
                        text: "-"
                        opacity: 0.8
                        onClicked: {
                            calcResults()
                        }
                    }
                }

                Text {
                    // Separator
                    width: 10
                }

                TextField {
                    id: tfNumber
                    font.pointSize: 18
                    // inputMask: "9"
                    maximumLength: 5
                    width: 150
                    inputMethodHints: Qt.ImhDigitsOnly | Qt.ImhNoPredictiveText
                    platformSipAttributes: customSipAttributes

                    onTextChanged: {
                        calcResults()
                    }

                    Keys.onReturnPressed: {
                        calcResults()
                        tfNumber.closeSoftwareInputPanel()
                    }

                    platformStyle: TextFieldStyle { paddingRight: clearButton.width }
                    Image {
                        id: clearButton
                        anchors.right: parent.right
                        anchors.verticalCenter: parent.verticalCenter
                        source: "image://theme/icon-m-input-clear"
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                inputContext.reset();
                                tfNumber.text = "";
                            }

                        }

                    }
                }

                Button {
                    id: btnSelectUnit
                    width: 130
                    text: sdUnit.model.get(sdUnit.selectedIndex).name
                    opacity: 0.5
                    onClicked: {
                        sdUnit.open();
                    }
                }
            }

            // Create a selection dialog with a title and list elements to choose from.
            SelectionDialog {
                id: sdUnit
                titleText: qsTr("Unit")
                selectedIndex: 3
                model: unitModel
                onAccepted: {
                    calcResults()
                }
            }

            ListModel {
                id: unitModel				
            }


            Row {
                id: rowCalcButtonAndResults
                x: 80
                y: 290
                Text {
                    opacity: 0.5
                    width: 30
                    text: qsTr("=")
                    font.pointSize: 18
                    font.bold: true
                }

                Text {
                    id: txtResults
                    font.pointSize: 18
                    font.bold: true
                    color: "#a20407"
                    width: 200
                }

            }

            Row {
                x: 10
                y: 360
                Button {
                    id: btnClear
                    width: 130
                    text: qsTr( "Clear" )
                    opacity: 0.5
                    onClicked: {
                        clear()
                    }
                }
            }
            Row {
                x: mainPage.width - 320
                y: 430

                Image {
                    id: imgCalcTimeDiff
                    x: 0; y: 0
                    width: 320;
                    source: qsTr("qrc:/icon_timediff")
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            appWindow.pageStack.clear()
                            appWindow.pageStack.push(timeDiffPage)
                        }
                    }
                }

            }

        }

        DatePickerDialog {
            id: dlgDate
            titleText: qsTr("Select a date")            
            minimumYear: 1900
            maximumYear: 2099
            acceptButtonText: qsTr("OK")
            rejectButtonText: qsTr("Cancel")
            onAccepted: selectDateCallbackFunction()
        }
    }

    function createUnitMenuItems() {
        // console.log("createUnitMenuItems() executed.")
        if (unitModel.count==0) {
            unitModel.append({"name":qsTr("Year(s)")})
            unitModel.append({"name":qsTr("Month(s)")})
            unitModel.append({"name":qsTr("Week(s)")})
            unitModel.append({"name":qsTr("Day(s)")})
            unitModel.append({"name":qsTr("Business Day(s)")})
            unitModel.append({"name":qsTr("Hour(s)")})
            unitModel.append({"name":qsTr("Minute(s)")})
            unitModel.append({"name":qsTr("Second(s)")})
            btnSelectUnit.text = sdUnit.model.get(sdUnit.selectedIndex).name
        }
    }

    function launchDialogToToday() {
        if (txtSelectedDate.text=="") {
            var dToday = new Date()
            dlgDate.year = dToday.getFullYear()
            dlgDate.month = dToday.getMonth()+1
            dlgDate.day = dToday.getDate()
        }
        dlgDate.open()
    }

    function selectDateCallbackFunction() {
        txtSelectedDate.text =  Qt.formatDateTime(new Date(dlgDate.year, dlgDate.month-1, dlgDate.day), "yyyy/MM/dd ddd")
        calcResults()
        // txtResults.text = ""
    }


    function clear() {
        tfNumber.text = ""
        txtSelectedDate.text = ""
        txtSelectedTime.text = ""
        txtResults.text = ""
        dlgTime.hour = 0
        dlgTime.minute = 0
        dlgTime.second = 0
    }

    function calcResults() {
        var dSelectedDate = new Date()
        var dResult = new Date()

        btnSelectUnit.text = sdUnit.model.get(sdUnit.selectedIndex).name

        if (txtSelectedDate.text == "") {
            dlgDate.year = dResult.getFullYear()
            dlgDate.month = dResult.getMonth() + 1
            dlgDate.day = dResult.getDate()
            txtSelectedDate.text = Qt.formatDateTime(dResult, "yyyy/MM/dd ddd")
        }

        if (txtSelectedTime.text != "") {
            dSelectedDate = new Date(dlgDate.year, dlgDate.month-1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second )
            dResult = dSelectedDate
        }
        else {
            dSelectedDate = new Date(dlgDate.year, dlgDate.month-1, dlgDate.day)
            dResult = dSelectedDate
        }

        var iPlusOrMinus = 1

        if (btnPlus.checked)
            iPlusOrMinus = 1
        else if (btnMinus.checked)
            iPlusOrMinus = -1

        var fDecimals = parseFloat(tfNumber.text) - Math.floor(parseFloat(tfNumber.text))

        if (btnSelectUnit.text==qsTr("Year(s)")) {
			if (iPlusOrMinus==1 || (dlgDate.year + (iPlusOrMinus * parseFloat(tfNumber.text)))>0 ) {			
				if (fDecimals > 0)
					dResult = new Date(dlgDate.year + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgDate.month-1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second + (fDecimals*365.25*24*60*60) )
				else
					dResult = new Date(dlgDate.year + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgDate.month-1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second)
			}
			else {	// handle B.C. years --- need to minus extra 1 year because there is no Year 0 by definition				
				if (fDecimals > 0)
					dResult = new Date(dlgDate.year + ( (iPlusOrMinus * (parseFloat(tfNumber.text) + 1) )), dlgDate.month-1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second - (fDecimals*365.25*24*60*60) )
				else
					dResult = new Date(dlgDate.year + ( (iPlusOrMinus * (parseFloat(tfNumber.text) + 1) )), dlgDate.month-1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second)								
			}
            // console.log("iPlusOrMinus = " + iPlusOrMinus + ", tfNumber = " + tfNumber.text + ", dResult = " + dResult)
		}

        if (btnSelectUnit.text==qsTr("Month(s)"))
            if (fDecimals > 0)
                dResult = new Date(dlgDate.year, dlgDate.month - 1 + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second + (fDecimals*30.436875*24*60*60) )
            else
                dResult = new Date(dlgDate.year, dlgDate.month - 1 + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second)

        if (btnSelectUnit.text==qsTr("Week(s)"))
            if (fDecimals > 0)
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day + ( iPlusOrMinus * parseFloat(tfNumber.text) * 7), dlgTime.hour, dlgTime.minute, dlgTime.second + (fDecimals*7*24*60*60) )
            else
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day + ( iPlusOrMinus * parseFloat(tfNumber.text) * 7), dlgTime.hour, dlgTime.minute, dlgTime.second)

        if (btnSelectUnit.text==qsTr("Day(s)"))
            if (fDecimals > 0)
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgTime.hour, dlgTime.minute, dlgTime.second + (fDecimals*24*60*60) )
            else
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgTime.hour, dlgTime.minute, dlgTime.second)

        if (btnSelectUnit.text==qsTr("Business Day(s)")) {
            if (fDecimals > 0) {
                dResult = CalcJSLib.addBusinessDays(dSelectedDate, (iPlusOrMinus * parseFloat(tfNumber.text)) )
                dResult = new Date(dResult.getFullYear(), dResult.getMonth(), dResult.getDate(), dlgTime.hour, dlgTime.minute, dlgTime.second + (fDecimals*24*60*60))
            }
            else
                dResult = CalcJSLib.addBusinessDays(dSelectedDate, (iPlusOrMinus * parseFloat(tfNumber.text)) )
        }

        if (btnSelectUnit.text==qsTr("Hour(s)"))
            if (fDecimals > 0)
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day, dlgTime.hour + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgTime.minute, dlgTime.second + (fDecimals*60*60) )
            else
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day, dlgTime.hour + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgTime.minute, dlgTime.second )

        if (btnSelectUnit.text==qsTr("Minute(s)"))
            if (fDecimals > 0)
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day, dlgTime.hour, dlgTime.minute + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgTime.second )
            else
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day, dlgTime.hour, dlgTime.minute + ( iPlusOrMinus * parseFloat(tfNumber.text)), dlgTime.second + (fDecimals*60))

        if (btnSelectUnit.text==qsTr("Second(s)"))
            if (fDecimals > 0)
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second  + ( iPlusOrMinus * parseFloat(tfNumber.text)) )
            else
                dResult = new Date(dlgDate.year, dlgDate.month - 1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second  + ( iPlusOrMinus * parseFloat(tfNumber.text)) + fDecimals )

        var sResults = ""
        if (txtSelectedTime.text != "")
            sResults = Qt.formatDateTime(dResult, "yyyy/MM/dd HH:mm:ss ddd").toString()
        else
            sResults = Qt.formatDateTime(dResult, "yyyy/MM/dd ddd").toString()

        if ( ( ( btnSelectUnit.text==qsTr("Year(s)") && (parseFloat(tfNumber.text) >= 1801) ) ||  ( btnSelectUnit.text==qsTr("Month(s)") && (parseFloat(tfNumber.text) >= 21612) ) )
                && iPlusOrMinus==-1 && dResult.getFullYear()>="1900" && dResult.getFullYear()<="1999" )
            sResults = "00" + sResults.substr(2,sResults.length-2)  // to cater the case where QML treats YY as 19YY


        if (sResults.substr(0,5) == "-4713") {
            dlgBefore4713BC.open()
            tfNumber.text = ""
        }

        if (tfNumber.text!="" && (!CalcJSLib.isValidDate(dResult) || sResults == "" ) )  {
            dlgInvalidValue.open()
            tfNumber.text = ""
        }
		
        if (sResults.substr(0,1)!="-")
            txtResults.text =  sResults
        else
            txtResults.text = sResults.substr(1, sResults.length-1).replace(" ", qsTr(" B.C. "))

    }

    QueryDialog {
        id: dlgInvalidValue
        titleText: qsTr("Error")
        acceptButtonText: qsTr("OK")
        message: qsTr("Please specify a proper value.")
    }	

    QueryDialog {
        id: dlgBefore4713BC
        titleText: qsTr("Reminder")
        acceptButtonText: qsTr("OK")
        message: qsTr("The earliest date that Time Calculator supports is 4713-01-02 B.C., i.e. the next day of the Julian Day.")
    }

    TimePickerDialog {
        id: dlgTime
        titleText: qsTr("Select a time")
        acceptButtonText: qsTr("OK")
        rejectButtonText: qsTr("Cancel")
        onAccepted: selectTimeCallbackFunction()
    }

    function launchDialogToTime(hour, minute) {
        if (txtSelectedTime.text=="") {
            var d = new Date()
            dlgTime.hour = d.getHours()
            dlgTime.minute = d.getMinutes()
            dlgTime.second = d.getSeconds()
        }
        dlgTime.hourMode = DateTime.TwentyFourHours
        dlgTime.fields = DateTime.Hours | DateTime.Minutes | DateTime.Seconds;
        dlgTime.open();
    }

    function selectTimeCallbackFunction() {
        txtSelectedTime.text =  Qt.formatDateTime(new Date(dlgDate.year, dlgDate.month, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second), "HH:mm:ss")
        calcResults()
        // txtResults.text = ""
    }    

    Component.onCompleted: createUnitMenuItems()
}
